package com.lagou.vo.rpc;


import com.lagou.vo.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;


import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list)
            throws Exception {
        if (null != byteBuf) {
            //在byteBuf缓冲区中标记当前的索引
            byteBuf.markReaderIndex();
            //获取当前索引
            int length = byteBuf.readableBytes();
            //创建一个初始化字节
            byte[] bytes = new byte[length];

            byteBuf.readBytes(bytes,byteBuf.readerIndex(),length);

            //反序列化
            list.add(serializer.deserialize(clazz,bytes));
        }
    }
}
